<template>
  <div class="search-container">
    <!-- 顶部导航 -->
    <TopNav />
    <!-- <div class="top-nav">
      <RouterLink to="/" class="nav-logo">
        <i class="fas fa-book-open"></i> 单词学习
      </RouterLink>
      <div class="nav-links">
        <RouterLink to="/home" class="nav-link">首页</RouterLink>
        <RouterLink to="/test" class="nav-link">测试</RouterLink>
        <RouterLink to="/search" class="nav-link active">搜索</RouterLink>
        <button class="logout-button" @click="logout">
          <i class="fas fa-sign-out-alt"></i> 退出
        </button>
      </div>
    </div>  -->

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-box">
        <input type="text" v-model="searchQuery" @keyup.enter="searchWord" placeholder="输入要搜索的单词..."
          class="search-input">
        <button @click="searchWord" class="search-button">
          <i class="fas fa-search"></i> 搜索
        </button>
      </div>

      <!-- 搜索建议 -->
      <div class="suggestions" v-if="suggestions.length > 0">
        <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item"
          @click="selectSuggestion(suggestion)">
          {{ suggestion.word }} - {{ suggestion.definition }}
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="results-section" v-if="searchResults">
      <div class="word-card" v-if="currentWord">
        <div class="word-header">
          <h2>{{ currentWord.word }}</h2>
          <span class="phonetic">/{{ currentWord.phonetic }}/</span>
          <button class="pronounce-btn" @click="pronounceWord(currentWord.word)">
            <i class="fas fa-volume-up"></i>
          </button>
        </div>

        <div class="word-details">
          <div class="detail-section">
            <h3><i class="fas fa-book"></i> 释义</h3>
            <p>{{ currentWord.definition }}</p>
          </div>

          <div class="detail-section">
            <h3><i class="fas fa-comment"></i> 例句</h3>
            <div class="example" v-for="(example, index) in currentWord.examples" :key="index">
              <p class="example-en">{{ example.en }}</p>
              <p class="example-cn">{{ example.cn }}</p>
            </div>
          </div>

          <div class="detail-section">
            <h3><i class="fas fa-exchange-alt"></i> 同义词</h3>
            <div class="synonyms">
              <span v-for="(synonym, index) in currentWord.synonyms" :key="index">
                {{ synonym }}{{ index < currentWord.synonyms.length - 1 ? '、' : '' }} </span>
            </div>
          </div>
        </div>

        <div class="word-actions">
          <button class="action-btn save-btn">
            <i class="fas fa-bookmark"></i> 保存
          </button>
          <button @click="see_detial(currentWord.word)" class="action-btn practice-btn">
            <i class="fas fa-pen"></i> 查看详细
          </button>
        </div>
      </div>

      <div class="no-results" v-else>
        <i class="fas fa-search-minus"></i>
        <p>没有找到 "{{ searchQuery }}" 的结果</p>
      </div>
    </div>
  </div>
  <wordDrawerTop :key="selectedWord" :word="selectedWord" :show="showDrawer" />
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import wordDrawerTop from "../../components/wordDrawerTop.vue";

import TopNav from "../../components/TopNav.vue";

const router = useRouter();
const searchQuery = ref('');
const searchResults = ref(null);
const suggestions = ref([]);
const currentWord = ref(null);
const CACHE_KEY = 'excelDataCache';
// 模拟搜索函数
const searchWord = () => {
  if (!searchQuery.value.trim()) return;

  // 模拟API调用
  setTimeout(() => {
    // 模拟搜索结果
    const mockResults = {
      word: searchQuery.value.toLowerCase(),
      phonetic: mockPhonetics[searchQuery.value.toLowerCase()] || 'ˈmɒk.ɪŋ',
      definition: mockDefinitions[searchQuery.value.toLowerCase()] || 'A word used for demonstration purposes',
      examples: [
        { en: `This is an example sentence using ${searchQuery.value}.`, cn: `这是一个使用${searchQuery.value}的例句。` },
        { en: `Can you think of another sentence with ${searchQuery.value}?`, cn: `你能想出另一个包含${searchQuery.value}的句子吗？` }
      ],
      synonyms: ['demo', 'sample', 'illustration']
    };

    currentWord.value = mockResults;
    searchResults.value = true;
    suggestions.value = [];
  }, 50);
};

// 选择搜索建议
const selectSuggestion = (suggestion) => {

  searchQuery.value = suggestion.word;
  searchWord();

};

// 发音功能
const pronounceWord = (word) => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(word);
    utterance.lang = 'en-US';
    speechSynthesis.speak(utterance);
  }
};

const see_detial = (word) => {
  console.log(word);
  openDrawer(word);
}


// 单词抽屉
const selectedWord = ref("");
const showDrawer = ref(false);

const openDrawer = async (word) => {
  if (showDrawer.value) {
    showDrawer.value = false;
    await nextTick();
  }
  selectedWord.value = word;
  setTimeout(() => {
    showDrawer.value = true;
  }, 10);
};



// 模拟数据
var mockDefinitions = {
  'example': 'a thing characteristic of its kind or illustrating a general rule',
  'search': 'try to find something by looking or otherwise seeking carefully and thoroughly',
  'word': 'a single distinct meaningful element of speech or writing'
};

var mockPhonetics = {
  'example': 'ɪɡˈzɑːm.pəl',
  'search': 'sɜːtʃ',
  'word': 'wɜːd'
};

var mockWords = ['example', 'search', 'word', 'dictionary', 'vocabulary'];
// 加载缓存数据
// 加载缓存数据
const loadFromCache = () => {
  const cached = localStorage.getItem(CACHE_KEY);
  if (cached) {
    try {
      const parsedCache = JSON.parse(cached);
      const decryptedData = JSON.parse(parsedCache.data);

      // 清空原有数据
      mockWords = [];
      mockDefinitions = {};
      mockPhonetics = {};

      // 重新填充数据
      decryptedData.forEach(item => {
        const [word, definition, phonetic] = item;
        if (word) {
          mockWords.push(word);
          if (definition) mockDefinitions[word] = definition;
          if (phonetic) mockPhonetics[word] = phonetic;
        }
      });

      console.log('从缓存加载的数据:', {
        words: mockWords,
        definitions: mockDefinitions,
        phonetics: mockPhonetics
      });

    } catch (error) {
      console.error('数据解析错误:', error);
      // 加载失败时恢复默认数据
      resetToDefaultData();
    }
  } else {
    console.log('没有找到缓存数据，使用默认数据');
  }
};

// 重置为默认数据
const resetToDefaultData = () => {
  mockWords = ['example', 'search', 'word', 'dictionary', 'vocabulary'];
  mockDefinitions = {
    'example': 'a thing characteristic of its kind or illustrating a general rule',
    'search': 'try to find something by looking or otherwise seeking carefully and thoroughly',
    'word': 'a single distinct meaningful element of speech or writing'
  };
  mockPhonetics = {
    'example': 'ɪɡˈzɑːm.pəl',
    'search': 'sɜːtʃ',
    'word': 'wɜːd'
  };
};



// 监听搜索输入变化
watch(searchQuery, (newVal) => {

  // console.log('搜索查询变化:', newVal);

  if (newVal.length > 2) {
    try {
      // 确保 mockWords 是数组且所有元素都是字符串
      if (!Array.isArray(mockWords)) {
        console.error('mockWords 不是数组');
        mockWords = [];
      }

      // 过滤并生成建议
      suggestions.value = mockWords
        .filter(word => {
          // 确保 word 是字符串
          const wordStr = String(word || '').toLowerCase();
          return wordStr.includes(newVal.toLowerCase());
        })
        .map(word => {
          const wordStr = String(word || '');
          return {
            word: wordStr,
            definition: mockDefinitions[wordStr] || 'A word in the dictionary'
          };
        });
      // console.log(suggestions.value.length, '个建议');

    } catch (error) {
      console.error('生成搜索建议时出错:', error);
      suggestions.value = [];
    }
  } else {
    suggestions.value = [];
  }
});

// 组件挂载时加载缓存数据
onMounted(() => {
  loadFromCache();
});



const logout = () => {
  localStorage.removeItem('token');
  router.push('/');
};
</script>

<style scoped lang="scss">
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.search-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
  min-height: 100vh;
  background-color: var(--bg-color);
}



.search-section {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1rem;

  .search-box {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
  }

  .search-input {
    flex: 1;
    padding: 1rem;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 1rem;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    transition: border 0.3s, box-shadow 0.3s;
    background: var(--bg-color);
    color: var(--text-color);

    &:focus {
      outline: none;
      border-color: #4a6bff;
      box-shadow: 0 2px 10px rgba(74, 107, 255, 0.2);
    }
  }

  .search-button {
    padding: 0 1.5rem;
    background: #7d95ff;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: background 0.3s;

    &:hover {
      background: #3a5bef;
    }

    i {
      margin-right: 0.5rem;
    }
  }

  .suggestions {
    background: var(--bg-color);
    border-radius: 8px;
    box-shadow: 0 2px 10px var(--shadow-color);
    max-height: 300px;
    overflow-y: auto;
  }

  .suggestion-item {
    padding: 1rem;
    border-bottom: 1px solid var(--border-color);
    cursor: pointer;
    transition: background 0.2s;
    color: var(--text-color-flag);

    &:hover {
      background: var(--card-bg);
    }

    &:last-child {
      border-bottom: none;
    }
  }
}

.results-section {
  max-width: 800px;
  margin: 0 auto 2rem;
  padding: 0 1rem;

  .word-card {
    background: var(--bg-color);
    border-radius: 12px;
    box-shadow: 0 0px 13px var(--shadow-color);
    padding: 2rem;
  }

  .word-header {
    display: flex;
    align-items: center;
    margin-bottom: 1.5rem;
    border-bottom: 1px solid var(--border-color);
    padding-bottom: 1rem;

    h2 {
      margin: 0;
      font-size: 2rem;
      color: #1e3c72;
      text-transform: capitalize;
    }

    .phonetic {
      margin: 0 1rem;
      color: var(--text-color);
      font-style: italic;
    }

    .pronounce-btn {
      background: none;
      border: none;
      color: #4a6bff;
      font-size: 1.2rem;
      cursor: pointer;
      transition: transform 0.2s;

      &:hover {
        transform: scale(1.1);
      }
    }
  }

  .word-details {
    .detail-section {
      margin-bottom: 1.5rem;

      h3 {
        display: flex;
        align-items: center;
        color: #1e3c72;
        margin: 0 0 0.5rem;
        font-size: 1.1rem;

        i {
          margin-right: 0.5rem;
          color: #4a6bff;
        }
      }

      p {
        margin: 0.5rem 0;
        line-height: 1.6;
        color: var(--text-color);
      }
    }

    .example {
      background: var(--bg-color-flag);
      padding: 0.8rem;
      border-radius: 6px;
      margin-bottom: 0.5rem;

      &-en {
        font-weight: 500;
        margin-bottom: 0.3rem;
      }

      &-cn {
        color: var(--text-color);
        font-size: 0.9rem;
      }
    }

    .synonyms {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;

      span {
        background: #e9ecef;
        padding: 0.3rem 0.8rem;
        border-radius: 20px;
        font-size: 0.9rem;
        color: #495057;
      }
    }
  }

  .word-actions {
    display: flex;
    gap: 1rem;
    margin-top: 2rem;

    .action-btn {
      flex: 1;
      padding: 0.8rem;
      border: none;
      border-radius: 8px;
      font-weight: 500;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;

      i {
        margin-right: 0.5rem;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .save-btn {
      background: var(--save-btn-color);
      color: #1976d2;

      &:hover {
        background: #bbdefb;
      }
    }

    .practice-btn {
      background: var(--practice-btn-color);
      color: #388e3c;

      &:hover {
        background: #c8e6c9;
      }
    }
  }

  .no-results {
    text-align: center;
    padding: 3rem;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

    i {
      font-size: 3rem;
      color: #adb5bd;
      margin-bottom: 1rem;
    }

    p {
      font-size: 1.2rem;
      color: #6c757d;
    }
  }
}

@media (max-width: 768px) {
  .top-nav {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;

    .nav-links {
      width: 100%;
      justify-content: space-between;
    }
  }

  .search-box {
    flex-direction: column;
  }

  .word-header {
    flex-wrap: wrap;
    gap: 0.5rem;

    h2 {
      font-size: 1.5rem !important;
    }
  }

  .word-actions {
    flex-direction: column;
  }
}
</style>